package com.builder.settings;

import com.builder.settings.interfaces.HelperStorage;
import com.builder.settings.interfaces.PropertiesStorage;
import com.gooddies.utils.KeyValue;
import com.swingson.SwingsonGuiBuilder;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JTable;

public class PropertyEditorDialog extends JDialog {

    private final JTable settingsTable = new JTable();
    private final PropertiesStorage properties;
    private final HelperStorage helper;
    private PropertiesTableModel model;
    private boolean modalResult = false;

    public PropertyEditorDialog(Window owner, PropertiesStorage properties, HelperStorage helper) {
        super(owner, ModalityType.DOCUMENT_MODAL);
        this.properties = properties;
        this.helper = helper;
        init();
    }

    private void init() {
        setTitle("Properties editor");
        List<KeyValue<String, String>> propertiesArray = new ArrayList<>();
        for (KeyValue<String, String> kv : properties.getProperties()) {
            propertiesArray.add(kv);
        }

        model = new PropertiesTableModel(propertiesArray);
        settingsTable.setModel(model);
        settingsTable.setDefaultRenderer(String.class, new PropertyCellRenderer(helper));
        model.fireTableStructureChanged();
        PropertyCellEditor editor = new PropertyCellEditor(helper, settingsTable);
        settingsTable.setCellEditor(editor);
        settingsTable.setRowHeight(24);
        settingsTable.getColumnModel().getColumn(0).setCellEditor(editor);
        settingsTable.addMouseMotionListener(new MouseAdapter() {

            @Override
            public void mouseMoved(MouseEvent e) {
                int row=settingsTable.rowAtPoint(e.getPoint());
                KeyValue<String, String>r=model.getRow(row);
                settingsTable.setToolTipText(helper.getHelp(r.getKey()));
            }
            
});
        SwingsonGuiBuilder.createGuiFromJsonInPackage(this);
        pack();
        setLocationRelativeTo(null);
    }

    private void saveProperties() {
        properties.setProperties(model.getValues());
    }

    private void onSave() {
        saveProperties();
        modalResult = true;
        setVisible(false);
        dispose();

    }

    private void onCancel() {
        setVisible(false);
        dispose();
    }
}
